﻿namespace JxcLite.Pages.BillData;

/// <summary>
/// 业务单据列表。
/// </summary>
public class BillList : BaseTablePage<JxBillHead>
{
    private IBillService Service;

    /// <summary>
    /// 取得业务单据类型（进货、进退货、销货、销退货）。
    /// </summary>
    protected virtual string Type { get; }

    protected override async Task OnInitPageAsync()
    {
        await base.OnInitPageAsync();
        Service = await CreateServiceAsync<IBillService>();
        Table.Toolbar.ShowCount = 6;
        Table.FormType = typeof(BillForm);
        Table.OnQuery = QueryBillsAsync;
        Table.Column(c => c.Status).Template((b, r) => b.Tag(r.Status));
        Table.Column(c => c.SettleMode).Template((b, r) => b.Tag(r.SettleMode));
        Table.Column(c => c.BillDate).Type(FieldType.Date);
    }

    public async void New()
    {
        var row = await Service.GetDefaultBillAsync(Type);
        Table.NewForm(Service.SaveBillAsync, row);
    }

    public void Edit(JxBillHead row) => Table.EditForm(Service.SaveBillAsync, row);
    public void DeleteM() => Table.DeleteM(Service.DeleteBillsAsync);
    public void Delete(JxBillHead row) => Table.Delete(Service.DeleteBillsAsync, row);

    public void Copy() => Table.SelectRow(async row =>
    {
        var row1 = await Service.GetDefaultBillAsync(Type);
        row1.Partner = row.Partner;
        row1.ContractNo = row.ContractNo;
        row1.InvoiceNo = row.InvoiceNo;
        row1.SettleMode = row.SettleMode;
        row1.Logistics = row.Logistics;
        row1.Note = row.Note;
        row.Lists = await Service.GetBillListsAsync(row.Id);
        Table.NewForm(Service.SaveBillAsync, row1);
    });

    public void Return() => Table.SelectRow(async row =>
    {
        var type = BillType.GetReturnType(row.Type);
        var row1 = await Service.GetDefaultBillAsync(type);
        row1.Partner = row.Partner;
        row1.ContractNo = row.ContractNo;
        row1.InvoiceNo = row.InvoiceNo;
        row1.SettleMode = row.SettleMode;
        row1.TotalAmount = row.TotalAmount;
        row1.Logistics = row.Logistics;
        row1.ReturnNo = row.BillNo;
        row1.Note = row.Note;
        row.Lists = await Service.GetBillListsAsync(row.Id);
        Table.NewForm(Service.SaveBillAsync, row1);
    });

    public void Print() => Table.SelectRow(async row =>
    {
        row.Lists = await Service.GetBillListsAsync(row.Id);
        await JS.PrintAsync<BillPrint>(f => f.Set(c => c.Model, row));
    });

    public async void Export() => await Table.ExportDataAsync();

    private Task<PagingResult<JxBillHead>> QueryBillsAsync(PagingCriteria criteria)
    {
        criteria.SetQuery(nameof(JxBillHead.Type), QueryType.Equal, Type);
        return Service.QueryBillsAsync(criteria);
    }
}